<?php

namespace app\api\controller\user;

use app\api\controller\BaseController;
use app\models\user\UserCar;
use app\Request;
use utils\Json;
use services\UtilService;

/**
 * 用户的车辆管理
 * Class CarController
 * @package app\api\controller\user
 */
class CarController extends BaseController
{
    /**
     * 获取我的所有的车辆
     * @param Request $request
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lst(Request $request)
    {
        return app("json")->success(UserCar::getUserCarList($request->uid())->toArray());
    }

    /**
     * 新增
     * @param Request $request
     * @return mixed
     */
    public function add(Request $request)
    {
        $userCar = new UserCar();
        $license_no = $request->param()["license_no"];
        if (!$license_no) return app("json")->fail("请填写车牌号");
        if ($userCar->add($request->uid(), $license_no))
            return app("json")->successful("车辆添加成功");
        else
            return app("json")->fail("添加车牌失败");
    }

    /**
     * 修改
     * @param Request $request
     * @return mixed
     */
    public function edit(Request $request)
    {
        list($car_id, $license_no) = UtilService::getMore([
            ["car_id", ""],
            ["license_no", ""]], $request, true
        );
        if (!$car_id) return app("json")->fail("车辆不存在");
        if (!$license_no) return app("json")->fail("请填写车牌号");
        if (UserCar::edit(["license_no" => $license_no], ["id" => $car_id]))
            return app("json")->successful("车辆修改成功");
        else
            return app("json")->fail("车辆修改失败");
    }

    /**
     * 删除车辆
     * @param Request $request
     * @param $car_id
     * @return mixed
     */
    public function del(Request $request, $car_id)
    {
        if (!$car_id) return app("json")->fail("车辆不存在");
        if (UserCar::where('id', $car_id)->update(["is_del" =>1]))
            return app("json")->successful("车辆删除成功");
        else
            return app("json")->fail("车辆删除失败");
    }
}